<?php

namespace App\Http\Controllers\Passport;

use App\Http\Controllers\Controller as BaseController;
use Illuminate\Http\Request;

class Oauth2Controller extends BaseController
{
    public function code() {
        $query = http_build_query([
            'client_id' => config('passport.oauth2.client_id'),
            'redirect_uri' => config('passport.oauth2.redirect_uri'),
            'response_type' => 'code',
            'scope' => '',
        ]);

        // var_dump($query);exit;

        return redirect(config('passport.oauth2.code_uri') .'?' . $query);

        // try {


        //     $client = new \GuzzleHttp\Client();
        //     // var_dump($client);exit;// object(GuzzleHttp\Client)#152 (1)

        //     $res = $client->request('GET', 'http://httpbin.org/get');

        //     var_dump($res->getStatusCode());
        //     // var_dump($res->getBody());
        //     // echo $res->getBody();
        //     // return json_decode((string) $response->getBody(), true);

        // } catch (\Exception $e) {
        //     var_dump($e->getMessage());
        // }
    }

    public function token(Request $request) {
        $http = new \GuzzleHttp\Client;

        $response = $http->post(config('passport.oauth2.token_uri'), [
            'form_params' => [
                'grant_type' => 'authorization_code',
                'client_id' => config('passport.oauth2.client_id'),
                'client_secret' => config('passport.oauth2.client_secret'),
                'redirect_uri' => config('passport.oauth2.redirect_uri'),
                'code' => $request->code,
            ],
        ]);

        // 按照微信与h5 的逻辑来说，这里应该获取用户信息，然后跳转到首页了。

        return json_decode((string) $response->getBody(), true);

        // $curl = curl_init();
        // curl_setopt($curl, CURLOPT_URL, config('passport.oauth2.token_uri'));
        // curl_setopt($curl, CURLOPT_POST, 1);
        // curl_setopt($curl, CURLOPT_POSTFIELDS, [
        //     'grant_type' => 'authorization_code',
        //     'client_id' => config('passport.oauth2.client_id'),
        //     'client_secret' => config('passport.oauth2.client_secret'),
        //     'redirect_uri' => config('passport.oauth2.redirect_uri'),
        //     'code' => $request->code,
        // ]);
        // curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        // $output = curl_exec($curl);
        // curl_close($curl);
        // var_dump($output);
    }
}